package install.ren.exercise.test.spring;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author zhuyunhui
 * @date 2019-07-21 20:52
 */
public class CglibMyBeanFactory implements MethodInterceptor {

    private final MyBean myBean;
    private static final Boolean DEFAULT_USE_PROXY = false;
    private volatile static CglibMyBeanFactory factory;

    private boolean useProxy;

    @Override
    public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        if ("hello".equals(method.getName())) {
            args[0] = " ,I get " + args[0];
        }

        return methodProxy.invokeSuper(target, args);
    }

    /**
     * @param useProxy 是否使用代理
     * @return
     */
    public static final MyBean getSingleton(Boolean useProxy) {
        if (factory == null) {
            synchronized (CglibMyBeanFactory.class) {
                if (factory == null) {
                    factory = new CglibMyBeanFactory(useProxy);
                }
            }
        }
        return factory.myBean;
    }

    private CglibMyBeanFactory(Boolean useProxy) {
        this.useProxy = useProxy;
        this.myBean = (MyBean)createObject(new MyBean());
    }

    private Object createObject(MyBean target) {
        if (!useProxy) {
            return target;
        }

        //加载需要创建子类的类
        Enhancer enhancer = new Enhancer();
        //设置代理目标
        enhancer.setSuperclass(target.getClass());
        //设置回调
        enhancer.setCallback(this);

        enhancer.setClassLoader(target.getClass().getClassLoader());
        //返回子类对象
        return enhancer.create();

    }
}
